﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
using System.Threading;

namespace SearchRS
{
    public class TorecSearcher : RSSearcher
    {
        private readonly string m_searchOrder;

        private const string c_startIndexTag = /*<td colspan=\"2\" class=\"newd_table_contentMiddleMiddle_BG\"><div>\r\n<!--START INDEX-->*/
            "<div class=\"sub_versions_scroll scroll_colors\"><p id=\"version_list\">";
                                                                                                                                          
        private const string c_endIndexTag = "</p></div>";//<!--END INDEX-->";

        public TorecSearcher(string searchOrder)
        {
            m_searchOrder = searchOrder;
        }

        public TorecResults Search(string torecLink)
        {
            TorecResults results = new TorecResults();

            ServicePointManager.Expect100Continue = false;
            Stream st = null;
            
            int tries = 0;
            WebResponse resp = null;
            while (tries < 20)
            {
                WebRequest req = NetworkServices.NetworkServices.SendGetRequest(torecLink,
                                                               "",//"Accept-Encoding: gzip, deflate", 
                                                               "Cookie: JSSESSIONID=81Q21PS0180NQ9T10G339205M3.O1110O; ym_pop_freq_expiration491640=Wed, 2 Sep 2009 17:45:12 UTC; ym_pop_freq491640=1; __utma=256733838.608426651.1251827109.1251827109.1251827109.1; __utmb=256733838; __utmc=256733838; __utmz=256733838.1251827109.1.1.utmccn=(direct)|utmcsr=(direct)|utmcmd=(none)",
                                                               "www.torec.net",
                                                               true);
                try
                {
                    resp = req.GetResponse();
                    st = resp.GetResponseStream();
                    break;
                }
                catch (WebException)
                {
                    tries++;
                    Thread.Sleep(10000);
                }
            }

            // number of retires exceeded
            if (st == null)
                return results;

            StreamReader sr = new StreamReader(st);
            string buffer = sr.ReadToEnd();

            int startPos = buffer.IndexOf(c_startIndexTag);
            if (startPos == -1)
            {
                return results;
            }
            startPos += +c_startIndexTag.Length;
            int endPos = buffer.IndexOf(c_endIndexTag, startPos);
            if (endPos == -1)
            {
                return results;
            }

            string translationVersions = buffer.Substring(startPos, endPos - startPos );
            List<string> versions = new List<string>();
            Regex r = new Regex("<span>(<[^>]+>)+(.+?)<br /></span>", RegexOptions.Singleline);
            if (r.Match(translationVersions).Success)
            {
                foreach (Match s in r.Matches(translationVersions))
                {
                    versions.Add(s.Groups[s.Groups.Count-1].Value);
                }
            }
//            string[] versions = translationVersions.Split(new[] { "<br /></span>" }, 50, StringSplitOptions.RemoveEmptyEntries);

            string[] patterns = m_searchOrder.Split('|');
            List<List<string>> candidates = new List<List<string>>(patterns.Length);
            for (int i = 0; i < patterns.Length; i++ ) candidates.Add(new List<string>());

            foreach (string version in versions)
            {
                for (int i = 0; i < patterns.Length; i++)
                {
                    string theVersion = version.Replace("\n", "");
                    if (theVersion.ToLower().Contains(patterns[i].ToLower()))
                    {
                        if (candidates[i] == null) candidates[i] = new List<string>();
                        candidates[i].Add(theVersion);
                        break;
                    }
                }
            }
            
            for (int i=0; i<candidates.Count; i++)
            {
                for (int j = 0; j < candidates[i].Count; j++)
                {
                    string chosen = candidates[i][j];
                    chosen = Utils.Utils.CleanName(chosen);
                    string subsLink = SearchTorecSubs(buffer, chosen);
                    results.AddResult(chosen, subsLink);
                }
            }

            return results;
        }

        private string SearchTorecSubs(string buffer, string chosen)
        {
            string subtitlesLink = "";

            // Search subtitles
            int startSubsPos = buffer.IndexOf("הורדת תרגום הסרט");
            if (startSubsPos == -1)
                startSubsPos = buffer.IndexOf("הורדת תרגום");

            if (startSubsPos != -1)
            {
                buffer = buffer.Substring(startSubsPos);                
            }

            startSubsPos = buffer.IndexOf("לפרק הקודם");
            if (startSubsPos > 0)
                buffer = buffer.Substring(startSubsPos);

            Regex subsVersions = new Regex("<option value=\"([^\"]+)\"[^>]+>([^<]+)</option>", RegexOptions.Singleline);
            Match match = subsVersions.Match(buffer);
            while (match.Success)
            {
                string versionTag = match.Groups[1].Value;
                string versionName = Utils.Utils.CleanName(match.Groups[2].Value);
                if (Utils.Utils.AllWordsIncluded(chosen.ToLower(), versionName.ToLower()))
                {
                    Regex subIdExp = new Regex(@"sub_id=([^'&]+)'");
                    match = subIdExp.Match(buffer);
                    if (match.Success)
                    {
                        string subId = match.Groups[1].Value;
                        subtitlesLink = GetSubsLink(versionTag, subId);
                    }
                    break;
                }
                match = match.NextMatch();
            }

            return subtitlesLink;
        }

        private string GetSubsLink(string code, string subs_id)
        {
            WebResponse resp;
            Stream st;
            string buffer = "";
            int tries = 10;

            //while (buffer.IndexOf(".zip") == -1 && tries > 0)
            while (buffer.IndexOf("ajax") == -1 && tries > 0)
            {

                WebRequest req = NetworkServices.NetworkServices.SendPostRequest(//subsRawLink.Replace("/torec.net", "/www.torec.net"),
                                                                                "http://www.torec.net/ajax/sub/download.asp",                                                                                                   
                                                                                "",
                                                                                //"Cookie: __utmc=256733838; __utma=256733838.1654501740.1255539956.1255889064.1255896057.3; __utmz=256733838.1255539956.1.1.utmccn=(direct)|utmcsr=(direct)|utmcmd=(none); __utmb=256733838; JSSESSIONID=8,QPQ00.0MQ9S,T01NNOPP9516N5.4M6P; ym_pop_freq_expiration491640=Mon, 19 Oct 2009 18:04:24 UTC; ym_pop_freq491640=1; Torec%2ENet%5FSF%5Fsub%5F " + subs_id + "=sub=10%2F18%2F2009+10%3A23%3A55+PM; Torec%2ENet%5FSF%5Fsite=userID=406265&userp=D5D1D7D8E5CBCBDB&user=maverick3434",
                                                                                "Cookie: __utma=256733838.2027542878.1292089131.1294864678.1296285645.6; __utmz=256733838.1292089131.1.1.utmccn=(direct)|utmcsr=(direct)|utmcmd=(none); __utmb=256733838; __utmc=256733838; p6165=yes; BVGDU=http%3A//www.hyperpromote.com/tags/showdsnrp1.html%3F111; BVGDT=21600; pBVPU=yes; Torec%2ENet%5FSF%5Fsite=userID=406265&userp=D5D1D7D8E5CBCBDB&user=maverick3434; ASPSESSIONIDSQCSCCSC=AADJICPBNJJEIMDBPHBEKGAH; ASPSESSIONIDCCTQBAQA=ELCKOMOBDDDANNECMBGFFKCA; ASPSESSIONIDAAQQACRB=OKIJKAPBAJEBPDPELKLIJEBF; ASPSESSIONIDCARQDARB=HEOJMOOBFEMHCGAJMHKBJNIA; Torec%5FNC%5Fsite=userID=406265&userp=D2D8C6DCE5B4C8E4&user=maverick3434",
                                                                                "sub_id=" + subs_id + "&code=" + code + "&sh=yes&guest=&timewaited=-1",
                                                                                "Referer: http://www.torec.net/sub.asp?sub_id=" + subs_id);                                                                                          
                try
                {
                    resp = req.GetResponse();
                    st = resp.GetResponseStream();
                    StreamReader sr = new StreamReader(st);
                    buffer = sr.ReadToEnd();
                    break;
                }
                catch (WebException)
                {
                    tries--;
                }
            }

            if (tries == 0)
                return "";

            //int pos = buffer.IndexOf(".zip");
            //int pos2 = buffer.LastIndexOf("/", pos);
            //string subsLink = "torec.net/zip_versions/" + buffer.Substring(pos2 , pos - pos2  + 4);
            string subsLink = "www.torec.net" + buffer;
            subsLink = "http://" + subsLink.Replace("//", "/");
            return subsLink;
        }

    }
}
